<?php
require_once 'calendarSyncCommon.php';

if(isset($_SESSION['user_id'])){    
    $loginUrl = sprintf("https://accounts.google.com/o/oauth2/auth?scope=%s&state=%s&redirect_uri=%s&response_type=code&client_id=%s&access_type=%s&approval_prompt=force", $scope, $state, $redirect_uri, $client_id, $access_type);

    //Oauth 2.0: exchange token for session token so multiple calls can be made to api
    if(isset($_REQUEST['code'])){
        $_SESSION['google_access_token'] = get_oauth2_token($_REQUEST['code']);
        
        $user = new InsightUser($_SESSION['user_id']);
        $user->google_token = $_SESSION['google_token'];
        $user->update();
    }
}
//returns session token for calls to API using oauth 2.0
function get_oauth2_token($code) {
    global $client_id;
    global $client_secret;
    global $redirect_uri;

    $oauth2token_url = "https://accounts.google.com/o/oauth2/token";
    $clienttoken_post = array(
    "code" => $code,
    "client_id" => $client_id,
    "client_secret" => $client_secret,
    "redirect_uri" => $redirect_uri,
    "grant_type" => "authorization_code"
    );
    
    $curl = curl_init($oauth2token_url);

    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $clienttoken_post);
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $json_response = curl_exec($curl);
    curl_close($curl);

    $authObj = json_decode($json_response);
    CalendarSyncUtil::debug('json reponse from google', $json_response);
    if (isset($authObj->refresh_token)){
    //refresh token only granted on first authorization for offline access
    //save to db for future use (db saving not included in example)
        global $refreshToken;
        $_SESSION['google_token'] = $authObj->refresh_token;
    }

    $accessToken = $authObj->access_token;
    return $accessToken;
}
?>
<html>
    <body>
        <?php if(!isset($_SESSION['user_id'])){ ?>
            <a href="sfdcOAuth.php">Please login to Salesforce first</a>
        <?php } else if(!isset($_SESSION['google_token'])){?>
            <a href="<?php echo $loginUrl ?>">Login with Google account using OAuth 2.0</a>
        <?php } else { ?>
            Google refresh token: <?php echo $_SESSION['google_token'];?><br />
            <a href="main.php">You can proceed to main page for executing sync process</a>
        <?php } ?>    
    </body>
</html>